package com.cmw.controller.global.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;

/**
 * @Remark Web请求拦截器
 * @Author 程明卫
 * @Date 2017-05-17 20:10
 */
public class WebRequestInterceptor extends HandlerInterceptorAdapter {
    static final Logger LOG = LoggerFactory.getLogger(WebRequestInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //用来标识是否是ajax类数据请求，在 GlobalExceptionHandler 中会根据此判定是Ajax请求还是普通页面请求
        if(existResponseBody(handlerMethod)){
            response.setContentType("application/json;application/xml;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1/*");
        }

        return true;
    }

    /**
     * 判断是否有加 @ResponseBody注解
     * @param handlerMethod
     * @return
     */
    private boolean existResponseBody(HandlerMethod handlerMethod){
        Annotation[] annotations = handlerMethod.getMethod().getDeclaredAnnotations();
        for(Annotation annotation : annotations){
            String annotationName = annotation.annotationType().getSimpleName();
            if(annotationName.equals("ResponseBody")){
                return true;
            }
        }
        return  false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       //System.out.println("postHandle...");
    }
}
